package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ResourceDto;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.Role;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResponse<RoleVo> getPageVo(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        // 1.设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 2.查询数据
        Role role = BeanUtil.toBean(roleDto, Role.class);
        Page<Role> rolePage = roleMapper.getPage(role);

        // 3.封装返回结果
        return PageResponse.of(rolePage, RoleVo.class);
    }

    @Override
    public void addRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public void updateRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public List<String> selectResourceByRoleId(Long roleId) {
        List<Resource> resources = roleMapper.selectResourceByRoleId(roleId);
        List<String> resourceList = new ArrayList<>();
        for (Resource resource : resources) {
            resourceList.add(resource.getResourceNo());
        }
        return resourceList;
    }
}
